package com.zofer.study.thread.abc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description 多线程打印ABC
 * 使用 Semaphore 打印ABC
 * @date: 2020/10/15 15:07
 */
public class ABCPrintBySemaphore {

    private static Semaphore aSemaphore = new Semaphore(1);
    private static Semaphore bSemaphore = new Semaphore(0);
    private static Semaphore cSemaphore = new Semaphore(0);

    static class ATask implements Runnable{
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    aSemaphore.acquire();
                    System.out.print("A");
                    bSemaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    static class BTask implements Runnable{
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    bSemaphore.acquire();
                    System.out.print("B");
                    cSemaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    static class CTask implements Runnable{
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    cSemaphore.acquire();
                    System.out.print("C");
                    aSemaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new ATask()).start();
        new Thread(new BTask()).start();
        new Thread(new CTask()).start();
    }
}
